package org.itv.nettysrv;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipelineCoverage;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;

@SuppressWarnings("deprecation")
@ChannelPipelineCoverage("all")
public class DiscardClientHandler extends SimpleChannelHandler {

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
			throws Exception {
		// TODO Auto-generated method stub
		// super.exceptionCaught(ctx, e);

		e.getCause().printStackTrace();
		Channel ch = e.getChannel();
		ch.close();
	}

	@Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
			throws Exception {
		// TODO Auto-generated method stub
		// super.channelConnected(ctx, e);
		Channel ch = e.getChannel();

		ChannelBuffer buf = ChannelBuffers.buffer(8);
		buf.writeLong(System.currentTimeMillis());

		ChannelFuture f = ch.write(buf);
		System.out.println("client buf:"+buf.getLong(0));

		f.addListener(new ChannelFutureListener() {

			public void operationComplete(ChannelFuture channelfuture)
					throws Exception {
				// TODO Auto-generated method stub
				channelfuture.getChannel().close();
			}

		});
	}

}
